package com.apes.fico.finance.service;

import com.apes.fico.finance.model.costcollect.StoreTasks;
import com.apes.fico.finance.respository.StoreTasksRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fico.finance.model.costcollect.StaffSalaries;
import com.apes.fico.finance.model.costcollect.StoreTasks;
import com.apes.fico.finance.respository.StoreTasksDao;
import com.apes.fico.finance.respository.StoreTasksRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.repository.WorkPostGroupRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: cyy
 * @create: 2022-12-13 14:20
 */
@Service("storeTasksService")
public class StoreTasksService extends DomainService {
    @Autowired
    private StoreTasksRepository storeTasksRepository;

    //定时任务按天统计营业额与毛利额
    private void saveAmt(SimpleRequest request) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        Date date = c.getTime();
        String months = DateUtil.format(date, "MM");
        String years = DateUtil.format(date, "YYYY");
        List<StoreTasks> storeTasksList = storeTasksRepository.findAllByYearMonth(months, years);
        storeTasksList.stream().forEach(storeTasks -> {
            Map<String, Object> map = storeTasksRepository.findAmt(months, years, storeTasks.getDept().getId());
            storeTasks.setBusinessAmt(Double.parseDouble(map.get("YYE").toString()));
            storeTasks.setGrossProfitsAmt(Double.parseDouble(map.get("MLE").toString()));
            storeTasksRepository.saveAndFlush(storeTasks);
            //推送订阅消息
            pushStoreTasksMsg(storeTasks);
        });
    }

    public Map save(SimpleRequest request) {
        List<StoreTasks> staffSalaries = JSON.parseArray(request.getJO().getString("storeTasks"), StoreTasks.class);
        staffSalaries.forEach(storeTasks -> {
            List<StoreTasks> all = storeTasksRepository.findAll(JpaDsl.toCriteriaByEq("dept.id", storeTasks.getDept().getId(),
                    "yearMonth", storeTasks.getYearMonth()));
            if (all.size() != 0) throw new RuntimeException("本月已创建,无法重复创建");
            storeTasks.setCreator(request.getPersonId());
        });
        List<StoreTasks> storeTasks = storeTasksRepository.saveAll(staffSalaries);
        //推送订阅消息
        pushStoreTasksMsg(storeTasks);
        return MapUtil.mapper("storeTasks", storeTasks);
    }

    private void pushStoreTasksMsg(List<StoreTasks> storeTasks){
        storeTasks.forEach(this::pushStoreTasksMsg);
    }

    private void pushStoreTasksMsg(StoreTasks order) {
        JSONObject json = new JSONObject();
        json.put("id", order.getId());

        // 推送消息
        OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
        wrapper.setSubscriber("fico.typeStore.createOrUpdateTypeStore");        // 调用的 esb 方法
        wrapper.setAggregateId("TS_"+order.getId());                        // 单号
        wrapper.setPayload(json.toJSONString());                            // 传入的消息体
        SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
    }

    public List findOneToList(SimpleRequest request) {
        JSONObject object = request.getJO();
        JSONArray jsonArray = SpringManager.getBean(StoreTasksDao.class).queryAllTransactionFlow(object);
        if(jsonArray.size() <= 0)throw new RuntimeException("暂无数据");
        List result = jsonArray.stream().map(
                item -> {
                    JSONObject jsonObject = (JSONObject) item;
                    return MapUtil.mapper(
                            "dept", SpringManager.getBean(DeptRepository.class).findOne(jsonObject.getString("DEPT_ID")),
                            "yearMonth", jsonObject.getString("YEAR_MONTH"),
                            "businessTasksAmt", jsonObject.getString("BUSINESS_TASKS_AMT"),
                            "grossProfitTasksAmt", jsonObject.getString("GROSS_PROFIT_TASKS_AMT"),
                            "businessAmt", jsonObject.getString("BUSINESS_AMT"),
                            "grossProfitsAmt", jsonObject.getString("GROSS_PROFIT_AMT"),
                            "subsidyAmt", jsonObject.getString("SUBSIDY_AMT"),
                            "rewardPunishmentAmt", jsonObject.getString("REWARD_PUNISHMENT_AMT"),
                            "summary", jsonObject.getString("SUMMARY")
                    );
                }
        ).collect(Collectors.toList());
        return result;
    }

    // 导入
    public Map importLogic(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        // 数据匹配
        // 数据校验 判断前端明细是否有数据
        JSONObject modelJson = getJO.getJSONObject("model");
        // 数据匹配
        List maps = builderResultList(getJO.getJSONObject("importData"));

        return MapUtil.mapper("items", maps, "msg", "");
    }

    private List builderResultList(JSONObject importData) {
        List resultList = new ArrayList<>();
        importData.forEach((sheetName, excelItems) -> {
            JSONArray importDataValueArray = (JSONArray) excelItems;
            importDataValueArray.forEach(excelItem -> {
                if (!"部门".equals(((JSONArray) excelItem).get(1).toString()) && !"部门".equals(((JSONArray) excelItem).get(2).toString())) {
                    Dept byName = SpringManager.getBean(DeptRepository.class).findByIdAndName(((JSONArray) excelItem).get(1).toString().trim());
                    Dept byName1 = SpringManager.getBean(DeptRepository.class).findByIdAndName(((JSONArray) excelItem).get(0).toString().trim());
                    if (Objects.isNull(byName) && Objects.isNull(byName1))
                        throw new RuntimeException("请检查数据:" + ((JSONArray) excelItem).get(1).toString());
                    if (Objects.nonNull(byName)) {
                        resultList.add(MapUtil.mapper(
                                "dept", byName,
                                "yearMonth", ((JSONArray) excelItem).get(2).toString(),
                                "businessTasksAmt", ((JSONArray) excelItem).size() > 3 && ((JSONArray) excelItem).get(3) != null ? ((JSONArray) excelItem).get(3).toString() : 0,
                                "grossProfitTasksAmt", ((JSONArray) excelItem).size() > 4 && ((JSONArray) excelItem).get(4) != null ? ((JSONArray) excelItem).get(4).toString() : 0,
                                "businessAmt", ((JSONArray) excelItem).size() > 5 && ((JSONArray) excelItem).get(5) != null ? ((JSONArray) excelItem).get(5).toString() : 0,
                                "grossProfitsAmt", ((JSONArray) excelItem).size() > 6 && ((JSONArray) excelItem).get(6) != null ? ((JSONArray) excelItem).get(6).toString() : 0,
                                "summary", ((JSONArray) excelItem).size() > 9 && ((JSONArray) excelItem).get(9) != null ? ((JSONArray) excelItem).get(9).toString() : null
                        ));
                    } else {
                        resultList.add(MapUtil.mapper(
                                "dept", byName1,
                                "yearMonth", ((JSONArray) excelItem).get(1).toString(),
                                "businessTasksAmt", ((JSONArray) excelItem).size() > 2 && ((JSONArray) excelItem).get(3) != null ? ((JSONArray) excelItem).get(2).toString() : 0,
                                "grossProfitTasksAmt", ((JSONArray) excelItem).size() > 3 && ((JSONArray) excelItem).get(3) != null ? ((JSONArray) excelItem).get(3).toString() : 0,
                                "businessAmt", ((JSONArray) excelItem).size() > 4 && ((JSONArray) excelItem).get(4) != null ? ((JSONArray) excelItem).get(4).toString() : 0,
                                "grossProfitsAmt", ((JSONArray) excelItem).size() > 5 && ((JSONArray) excelItem).get(5) != null ? ((JSONArray) excelItem).get(5).toString() : 0,
                                "summary", ((JSONArray) excelItem).size() > 8 && ((JSONArray) excelItem).get(8) != null ? ((JSONArray) excelItem).get(8).toString() : null
                        ));
                    }
                }
            });
        });
        return resultList;
    }
}
